﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects;
using System.Diagnostics;
using Mani.Common.Security;

namespace Niazi.CRM.Business.Model
{

    public partial class CRMModelContainer
    {

        partial void OnContextCreated()
        {
            this.SavingChanges += new EventHandler(SaveTimeStamps);
            this.SavingChanges += new EventHandler(CheckOrder);
        }

        private void CheckOrder(object sender, EventArgs e)
        {
            foreach (ObjectStateEntry entry in
            ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(
            EntityState.Added | EntityState.Modified | EntityState.Deleted))
            {
                if (entry.Entity is Order && entry.State == EntityState.Modified)
                {
                    throw new Exception("ویرایش سفارش و بارنامه مجاز نمی باشد.");
                }

                if (entry.State == EntityState.Deleted)
                {
                    Order o = (Order)entry.Entity;
                    List<Accounting> accountings = this.Accountings.Where(a => a.OrderId == o.Id).ToList();
                    foreach (var item in accountings)
                    {
                        this.Accountings.DeleteObject(item);
                    }
                }
            }
        }

        private void SaveTimeStamps(object sender, EventArgs e)
        {
            foreach (ObjectStateEntry entry in
            ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(
            EntityState.Added | EntityState.Modified ))
            {
                if (entry.Entity is IAuditable)
                {
                    SecurityManager securityManager = new SecurityManager();
                    securityManager.authProvider = new WebAuthorizationProvider();
                    aspnet_Users user = securityManager.authProvider.GetCurrentUser();
                    if (user != null)
                        ((IAuditable)entry.Entity).Operator = user.UserId;

                    switch (entry.State)
                    {
                        case EntityState.Added:
                            ((IAuditable)entry.Entity).CreateDate = DateTime.Now;
                            ((IAuditable)entry.Entity).LastUpdate = DateTime.Now;
                            break;
                        case EntityState.Modified:
                            ((IAuditable)entry.Entity).LastUpdate = DateTime.Now;
                            break;
                    }
                }
            }
        }
    }
    
}
